package cn.deali.homework9.service;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.annotation.Nullable;

import java.io.IOException;

public class MusicService extends Service {
    private static final String TAG = MusicService.class.getName();

    @Nullable
    private MediaPlayer player = new MediaPlayer();

    private MusicBinder musicBinder = new MusicBinder();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return musicBinder;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mp.seekTo(0);//循环播放
                mp.start();
            }
        });
    }


    @Override
    //关闭后台停止播放
    public void onDestroy() {
        super.onDestroy();
        //先停止 再释放
        if (player.isPlaying()) {
            player.stop();
        }
        player.release();
        Log.d("tip", "had destroy");
    }

    public void loadMediaFile(String filepath) {
        try {
            // 设置音频文件到MediaPlayer对象中
            player.setDataSource(filepath);
            // 让MediaPlayer对象准备
            player.prepare();
        } catch (IOException ex) {
            Log.e(TAG, "加载媒体文件出错！");
            ex.printStackTrace();
        }
    }


    //主页面要调用的内容
    public class MusicBinder extends Binder {
        public void loadFile(String filepath) {
            loadMediaFile(filepath);
        }

        public void reset() {
            player.reset();
        }

        //判断是否正在播放
        public boolean isPlaying() {
            return player.isPlaying();
        }

        //播放或暂停
        public void play() {
            if (player.isPlaying()) {
                player.pause();
            } else {
                player.start();
            }
        }

        //停止播放
        public void stop() {
            if (player != null) {
                player.stop();
            }
        }

        public void closePlayer() {
            if (player != null) {
                player.stop();
                player.release();
            }
        }

        /**
         * 获取歌曲长度
         **/
        public int getProgress() {

            return player.getDuration();
        }

        /**
         * 获取播放位置
         */
        public int getPlayPosition() {

            return player.getCurrentPosition();
        }

        /**
         * 播放指定位置
         */
        public void seekToPositon(int msec) {
            player.seekTo(msec);
        }
    }
}

